package ldh.im.fxgui.controller;

import com.fluxvend.svgfx.SvgImageView;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;
import ldh.im.fxbase.component.VideoView;
import ldh.im.fxbase.data.pojo.ImUser;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.handle.WebRtcClient;
import ldh.im.fxgui.handle.WebRtcUiEvent;
import ldh.im.fxgui.util.UiUtil;
import ldh.im.fxgui.util.UserHeadImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

// 语音聊天
public class WebRtcAudioController extends WebRtcBaseController implements Initializable, WebRtcUiEvent {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebRtcAudioController.class);

    @FXML private SvgImageView speakerSvgView;
    private boolean speakerValue = false;

    public void setParams(String invitationUserId, String roomName, Set<String> userIdSet, double screenWidth, double screenHeight) {
        this.invitationUserId = invitationUserId;
        this.roomName = roomName;
        this.isAccept = this.roomName != null;
        this.isAudio = true;

        if (userIdSet.size() == 1) {
            initP2pPane(flowPane, userIdSet.iterator().next());
        } else {
            initGroupPane(flowPane, userIdSet);
        }
        initUi();

        String loginUserId = UiUtil.getLoginImUser().getUserId();
        webRtcClient = new WebRtcClient(this, loginUserId, roomName, true, screenWidth, screenHeight);

        this.startSignalWebSocket(userIdSet, "语音聊天");

        playCallSound();
    }

    @Override
    public void exitRoom(String userId, boolean isReceiver) {
        super.exitRoom(userId, isReceiver);
    }

    @Override
    public void receive(String userId, VideoView videoView) {
        stopCallSound();
    }

    @FXML
    public void close() {
        super.close();
    }

    @FXML
    private void switchSpeakerEvent(MouseEvent event) {
        this.speakerValue = !this.speakerValue;
        if (this.speakerValue) {
            this.speakerSvgView.setSvg(this.getClass().getResource("/webrtc-img/volume.svg").toExternalForm());
        } else {
            this.speakerSvgView.setSvg(this.getClass().getResource("/webrtc-img/volume_close.svg").toExternalForm());
        }
    }

    @Override
    public void localMediaCreated() {
        LOGGER.info("local media created!");
//        this.playCallSound();
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

    }

    @Override
    public Node getRoot() {
        return container;
    }

    private void initGroupPane(FlowPane flowPane, Set<String> userIdSet) {
        String loginUserId = UiUtil.getLoginImUser().getUserId();
        List<Label> labelList = userIdSet.stream().filter((u)->!u.equals(loginUserId))
                        .map(userId-> buildAvUserImage(userId)).collect(Collectors.toList());
        flowPane.getChildren().addAll(labelList);
        flowPane.setVgap(10);
        flowPane.setHgap(10);
    }

    private void initP2pPane(FlowPane flowPane, String remoteUserId) {
        VBox vBox = new VBox();
        vBox.setAlignment(Pos.CENTER);

        vBox.getChildren().addAll(buildAvUserImage(remoteUserId));
        vBox.setSpacing(10);

        userNodeViewMap.put(remoteUserId, vBox);
        flowPane.getChildren().addAll(vBox);
    }

    private Label buildAvUserImage(String userId) {
        ImUser imUser = ImCacheFactory.getInstance().getUser(userId);
        ImageView imageView = new ImageView();
        String headImg = imUser.getHeadImg();
        Image image = UserHeadImageUtil.getHeadImage(headImg);
        imageView.setImage(image);
        imageView.setFitWidth(WebRtcClient.videoWidth);
        imageView.setFitHeight(WebRtcClient.videoHeight);

        Label label = new Label(imUser.getUserName());
        label.setGraphic(imageView);
        label.setContentDisplay(ContentDisplay.TOP);

        userNodeViewMap.put(userId, label);
        return label;
    }
}
